﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//
using System.IO;
using System.Drawing;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;

namespace iPublic.API
{
    public partial class ShiBie
    {
        private const String host = "http://object.market.alicloudapi.com";
        private const String path = "/v2/object/recognize";
        private const String method = "POST";
        /// <summary>
        /// AppKey：24533420     AppSecret：c184cf030356721bbf111be41abad4ee 复制
        /// AppCode：bdc5a9bf1667487ba92779f03a0d2c1f
        /// </summary>
        private const String appcode = "bdc5a9bf1667487ba92779f03a0d2c1f";
        //提示信息
        public iDefine.showInfoProc showInfoProc = null;


        /// <summary>
        /// 飞搜识别。
        /// 网址：https://market.aliyun.com/products/57124001/cmapi014400.html?spm=5176.2020520132.101.13.OgJ2vd#sku=yuncode840000000
        /// </summary>
        /// <returns>处理结果</returns>
        public iDefine.ChuLiJieGuo shiBie(string sFile)
        {
            iDefine.ChuLiJieGuo result = new iDefine.ChuLiJieGuo(), jg = null;
            //
            String querys = "";
            string s = "", sBase64 = "", sInfo = "", bodys = "";
            Image img = null;

            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            try
            {
                img = new Bitmap(sFile);
                jg = imgToBase64(img, ref sBase64);
                //"{\"img_url\":your url// or \"img_base64\":your base64}";
                bodys = "{\"img_base64\":\"" + sBase64 + "\"}";

                //
                if (0 < querys.Length)
                {
                    url = url + "?" + querys;
                }

                if (host.Contains("https://"))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                }
                else
                {
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                }
                httpRequest.Method = method;
                httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
                //根据API的要求，定义相对应的Content-Type
                httpRequest.ContentType = "application/json; charset=UTF-8";
                //httpRequest.Headers.Add("Content-Type", "application/json");
                if (0 < bodys.Length)
                {
                    byte[] data = Encoding.UTF8.GetBytes(bodys);
                    using (Stream stream = httpRequest.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                
                try
                {
                    httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    httpResponse = (HttpWebResponse)ex.Response;
                }

                s = "识别:Status=" + httpResponse.StatusCode + ",method=" + httpResponse.Method + "headers=" + httpResponse.Headers;
                showInfo(s);
                //发到服务器识别，取返回值
                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                s = reader.ReadToEnd();
                //分析返回值
                if (s.ToUpper().Contains("\"RESULT\""))
                {   //正确：{"result":[{"id":"664","probability":0.2197652906179428,"description":"显示器","description_en":"monitor"},{"id":"1341","probability":0.13619302213191986,"description":"显示器","description_en":"display, video display"}],"final_time":1111}
                    iDefine.jsonShibieOK sbok = JsonConvert.DeserializeObject<iDefine.jsonShibieOK>(s);
                    result.data = sbok;
                    result.error = 0;
                    result.message = "ok";
                }
                else
                {   //错误：{"msg":"Missing argument: img_file/img_url/img_base64","code":1003}
                    iDefine.jsonShibieErr sber = JsonConvert.DeserializeObject<iDefine.jsonShibieErr>(s);
                    result.data = sber;
                    result.error = Convert.ToInt32(sber.code);
                    result.message = sber.msg;
                }
            }
            catch (Exception x)
            {
                result.error = 100;
                result.message = x.Message;
            }
            finally
            {
                if (img != null) img.Dispose();     //必须释放
                img = null;
            }
            return result;
        }

        

        #region //图片和base64字符串的互相转化
        /// <summary>
        /// 图片转成base64字符串
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="base64">base64字符串</param>
        /// <returns>成功与否的结果</returns>
        public iDefine.ChuLiJieGuo imgToBase64(Image img, ref string base64)
        {
            iDefine.ChuLiJieGuo result = new iPublic.iDefine.ChuLiJieGuo();
            MemoryStream ms = null;
            try
            {
                //BinaryFormatter binFormatter = new BinaryFormatter();
                //MemoryStream memStream = new MemoryStream();
                //binFormatter.Serialize(memStream, img);
                //byte[] bytes = memStream.GetBuffer();
                //base64 = Convert.ToBase64String(bytes);

                ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                base64 = Convert.ToBase64String(arr);
                
                //完成
                result.error = 0;
            }
            catch (Exception x)
            {
                result.error = 100;
                result.message = x.Message;
            }
            finally
            {
                if (ms != null) ms.Close(); //释放资源
            }
            return result;
        }

        /// <summary>
        /// bsse64字符串转成图片
        /// </summary>
        /// <param name="base64">base64字符串</param>
        /// <param name="img">返回处理了的图片</param>
        /// <returns>处理结果</returns>
        public iDefine.ChuLiJieGuo base64ToImage(string base64, ref Image img)
        {
            iDefine.ChuLiJieGuo result = new iDefine.ChuLiJieGuo();
            MemoryStream ms = null;
            try
            {
                byte[] bytes = Convert.FromBase64String(base64);
                ms = new MemoryStream(bytes);
                //BinaryFormatter binFormatter = new BinaryFormatter();
                //img = (Image)binFormatter.Deserialize(ms);
                img = new Bitmap(ms);

                //完成
                result.error = 0;
                result.message = "ok";
            }
            catch (Exception x)
            {
                result.error = 100;
                result.message = x.Message;
            }
            finally
            {
                if (ms != null) ms.Close();
            }
            return result;
        }
        #endregion


        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   //用于https的检查
            return true;
        }

        public void showInfo(string sInfo, bool lTime = true)
        {   //显示信息
            if (showInfoProc == null) return;
            showInfoProc(sInfo, lTime);
        }

    }


}